var key = "ac9a29dd78fc7192a4160d255b7b16cb";
var uri = "http://restapi.amap.com/v3/geocode/geo?key="+key+"&s=rsv3";
//http://restapi.amap.com/v3/geocode/geo?address=%E5%8C%97%E4%BA%AC%E5%B8%82%E6%B5%B7%E6%B7%80%E5%8C%BA%E8%8B%8F%E5%B7%9E%E8%A1%97&key=ac9a29dd78fc7192a4160d255b7b16cb&s=rsv3
var mapObj, mapMarker;
var marker = new Array();
var windowsArr = new Array();
var clearMap = true;
function getLocation(address){
	var url = uri + "&address="+encodeURIComponent(address);
	$.getJSON(url, function(res){
		return res;
	});
}

$(function () {
	mapInit();
})

//初始化地图对象，加载地图
function mapInit(){
	var lng = $('input[name="longitude"]').val();
    if(lng == null || lng == "null" || lng == ""){return;}
	var lat = $('input[name="latitude"]').val();
	mapObj = new AMap.Map("iCenter");
	//在地图中添加ToolBar插件
	mapObj.plugin(["AMap.ToolBar"],function(){		
		toolBar = new AMap.ToolBar();
		mapObj.addControl(toolBar);		
	});
	
	AMap.event.addListener(mapObj,'click',getLnglat);
	AMap.event.addListener(mapObj,'zoomchange',getMapZoom);
	//设置中心点
	//mapObj.setZoomAndCenter(14, new AMap.LngLat(lng, lat));
    var lnglatXY = new AMap.LngLat(lng,lat);
	mapObj.setCenter(lnglatXY);
    geocoder(lnglatXY);
	
	createMapMarker(lng, lat);
	mapObj.setFitView(); //调整到合理视野
	//setCity();
	getMapZoom();
}

//已知点坐标
	function geocoder(evt) {
		var MGeocoder;
		//加载地理编码插件
		AMap.service(["AMap.Geocoder"], function() {        
			MGeocoder = new AMap.Geocoder({ 
				radius: 1000,
				extensions: "all"
			});
			//逆地理编码
			MGeocoder.getAddress(evt, function(status, result){
				if(status === 'complete' && result.info === 'OK'){
					geocoder_CallBack(result);
				}
			});
		});
	}
	
	//回调函数
	function geocoder_CallBack(data) {
		var resultStr = "";
		var poiinfo="";
		var address;
		//返回地址描述
	   address = data.regeocode.formattedAddress;
       $("#device_address").html("[" + address + "," + data.regeocode.crosses[0].first_name + "与" + data.regeocode.crosses[0].second_name + "交叉口附近" + "]");
	}  

//显示当前位置结束


//鼠标在地图上点击，获取经纬度坐标
function getLnglat(e){  
	var lng = e.lnglat.getLng();
	var lat = e.lnglat.getLat(); 
	document.getElementById("lngX").value = lng;
	document.getElementById("latY").value = lat;
	createMapMarker(lng, lat);
} 
//经纬度坐标转换为地理像素坐标
function fromLngLatToContainerPixel(){  
	var px = document.getElementById("lngX").value;  
	var py = document.getElementById("latY").value;  
	var pixel=mapObj.lnglatToPixel(new AMap.LngLat(px,py),10);  
	document.getElementById("pixelx").value=pixel.getX();  
	document.getElementById("pixely").value=pixel.getY();  
}  

//地理像素坐标转换为经纬度坐标
function fromContainerPixelToLngLat(){  
	var lnglatX=parseInt(document.getElementById("pixelx").value);  
	var lnglatY=parseInt(document.getElementById("pixely").value);  
	var ll=mapObj.pixelToLngLat(new AMap.Pixel(lnglatX,lnglatY),10);  
	document.getElementById("lngX").value=ll.getLng();  
	document.getElementById("latY").value=ll.getLat();  
}
function getMapZoom(){
	var mapZoom = mapObj.getZoom();
	$("#mapZoom").val(mapZoom);
}
function setMapZoom(num){
	mapObj.setZoom(num);
}
function setCity(){
	var cityName = $('#queryCityName').val();
	if(!cityName){
		cityName = '上海市';
		$('#queryCityName').val(cityName);
	}
	mapObj.setCity(cityName);
}
$("#resetMapCenter").click(function(e) {
	var lng = $('input[name="longitude"]').val();
	var lat = $('input[name="latitude"]').val();
    mapObj.setCenter(new AMap.LngLat(lng, lat));
	createMapMarker(lng, lat);
});
$("#setCustomCenter").click(function(e) {
	var lng = $('#lngX').val();
	var lat = $('#latY').val();
    mapObj.setCenter(new AMap.LngLat(lng, lat));
	createMapMarker(lng, lat);
});
$("#queryCoords").click(function(e) {
    var Coords = $('#queryCoordsNums').val();
	Coords = Coords.split(',');
	var lng = Coords[0];
	var lat = Coords[1];
    mapObj.setCenter(new AMap.LngLat(lng, lat));
	clearMap = false;
	createMapMarker(lng, lat);
});
$("#queryCorrectCoords").click(function(e) {
    var Coords = $('#queryCorrectCoordsNums').val();
	Coords = Coords.split(',');
	var lng = Coords[0];
	var lat = Coords[1];
    mapObj.setCenter(new AMap.LngLat(lng, lat));
	clearMap = false;
	createMapMarker(lng, lat);
});
$("#getCorrectCoords").click(function(e) {
    var Coords = $('#queryCoordsNums').val();
	var url = BASE_URI;
	url += '/utils/gps_correct?gps=' + Coords;
	$.getJSON(url, function(res){
		if('undefined' == res || res.error > 0){
			Ucenter.alert(res);
		}else{
			//var data = $.parseJSON(res.datas);
			//var location = data[0].location.split(',');
//			$('[name="longitude"]').val(res.lng);
//			$('[name="latitude"]').val(res.lat);

			$("#queryCorrectCoordsNums").val(res.correct_coords);
		}
	});
});

$("#queryCity").click(function(e) {
    setCity();
});
$("#setMapZoom").click(function(e) {
	var num = $('#mapZoom').val();
	if(!num){
		num = 14;
		$('#mapZoom').val(num);
	}
    setMapZoom(num);
});
$("#updateCoords").click(function(e) {
    var lng = $('#lngX').val();
	var lat = $('#latY').val();
	$('input[name="longitude"]').val(lng);
	$('input[name="latitude"]').val(lat);
	//更新数据
});
function createMapMarker(lng, lat){
	if(clearMap){
		mapObj.clearMap();
	}
	mapMarker = new AMap.Marker({
      	map : mapObj,
      	position : new AMap.LngLat(lng, lat),
		draggable:true, //点标记可拖拽
		cursor:'move',  //鼠标悬停点标记时的鼠标样式
		//raiseOnDrag:true//鼠标拖拽点标记时开启点标记离开地图的效果
	});
    //marker.setMap(mapObj);
	
	showInfoWindow(lng, lat);
	AMap.event.addListener(mapMarker,'click',function(){
		showInfoWindow(lng, lat);
		$("#lngX").val(lng);
		$("#latY").val(lat);
    });
	AMap.event.addListener(mapMarker,'dragstart',function(){
		mapObj.clearInfoWindow();
    });
	AMap.event.addListener(mapMarker,'dragging',function(){
		var coords = mapMarker.getPosition();
		coords = coords.toString().split(",");
		$("#lngX").val(coords[0]);
		$("#latY").val(coords[1]);
    });
	AMap.event.addListener(mapMarker,'dragend',getLnglat);
	getMapZoom();
}
function showInfoWindow(lng, lat){
	//实例化信息窗体
	var infoWindow = new AMap.InfoWindow({
			isCustom:true,  //使用自定义窗体
			content:createInfoWindow('经纬度坐标', "经度："+lng+"<br/>纬度："+lat),
			offset:new AMap.Pixel(16, -45)//-113, -140
	});
	infoWindow.open(mapObj,mapMarker.getPosition());
}


//构建自定义信息窗体	
function createInfoWindow(title,content){
	var info = document.createElement("div");
	info.className = "info";

	//可以通过下面的方式修改自定义窗体的宽高
	//info.style.width = "400px";

	// 定义顶部标题
	var top = document.createElement("div");
	top.className = "info-top";
	  var titleD = document.createElement("div");
	  titleD.innerHTML = title;
	  var closeX = document.createElement("img");
	  closeX.src = "http://webapi.amap.com/images/close2.gif";
	  closeX.onclick = closeInfoWindow;
	  
	top.appendChild(titleD);
	top.appendChild(closeX);
	info.appendChild(top);
	
    
	// 定义中部内容
	var middle = document.createElement("div");
	middle.className = "info-middle";
	middle.style.backgroundColor='white';
	middle.innerHTML = content;
	info.appendChild(middle);
	
	// 定义底部内容
	var bottom = document.createElement("div");
	bottom.className = "info-bottom";
	bottom.style.position = 'relative';
	bottom.style.top = '0px';
	bottom.style.margin = '0 auto';
	var sharp = document.createElement("img");
	sharp.src = "http://webapi.amap.com/images/sharp.png";
	bottom.appendChild(sharp);	
	info.appendChild(bottom);
	return info;
}

//关闭信息窗体
function closeInfoWindow(){
	mapObj.clearInfoWindow();
}

//输入提示
function autoSearch() {
    var keywords = document.getElementById("keyword").value;
    var auto;
    //加载输入提示插件
        AMap.service(["AMap.Autocomplete"], function() {
        var autoOptions = {
            city: "" //城市，默认全国
        };
        auto = new AMap.Autocomplete(autoOptions);
        //查询成功时返回查询结果
        if ( keywords.length > 0) {
            auto.search(keywords, function(status, result){
            	autocomplete_CallBack(result);
            });
        }
        else {
            document.getElementById("result1").style.display = "none";
        }
    });
}
 
//输出输入提示结果的回调函数
function autocomplete_CallBack(data) {
    var resultStr = "";
    var tipArr = data.tips;
    if (tipArr&&tipArr.length>0) {                 
        for (var i = 0; i < tipArr.length; i++) {
            resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById(" + (i + 1)
                        + ",this)' onclick='selectResult(" + i + ")' onmouseout='onmouseout_MarkerStyle(" + (i + 1)
                        + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";
        }
    }
    else  {
        resultStr = " π__π 亲,人家找不到结果!<br />要不试试：<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
    }
    document.getElementById("result1").curSelect = -1;
    document.getElementById("result1").tipArr = tipArr;
    document.getElementById("result1").innerHTML = resultStr;
    document.getElementById("result1").style.display = "block";
}
 
//输入提示框鼠标滑过时的样式
function openMarkerTipById(pointid, thiss) {  //根据id打开搜索结果点tip 
    thiss.style.background = '#CAE1FF';
}
 
//输入提示框鼠标移出时的样式
function onmouseout_MarkerStyle(pointid, thiss) {  //鼠标移开后点样式恢复 
    thiss.style.background = "";
}
 
//从输入提示框中选择关键字并查询
function selectResult(index) {
    if(index<0){
        return;
    }
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById("keyword").onpropertychange = null;
        document.getElementById("keyword").onfocus = focus_callback;
    }
    //截取输入提示的关键字部分
    var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
	var cityCode = document.getElementById("divid" + (index + 1)).getAttribute('data');
    document.getElementById("keyword").value = text;
    document.getElementById("result1").style.display = "none";
    //根据选择的输入提示关键字查询
    mapObj.plugin(["AMap.PlaceSearch"], function() {       
        var msearch = new AMap.PlaceSearch();  //构造地点查询类
        AMap.event.addListener(msearch, "complete", placeSearch_CallBack); //查询成功时的回调函数
		msearch.setCity(cityCode);
        msearch.search(text);  //关键字查询查询
    });
}
 
//定位选择输入提示关键字
function focus_callback() {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        document.getElementById("keyword").onpropertychange = autoSearch;
   }
}
 
//输出关键字查询结果的回调函数
function placeSearch_CallBack(data) {
    //清空地图上的InfoWindow和Marker
    windowsArr = [];
    marker     = [];
    mapObj.clearMap();
    var resultStr1 = "";
    var poiArr = data.poiList.pois;
    var resultCount = poiArr.length;
    for (var i = 0; i < resultCount; i++) {
        resultStr1 += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><b><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></b>";
            resultStr1 += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
            addmarker(i, poiArr[i]);
    }
    mapObj.setFitView();
    document.getElementById("result").innerHTML = resultStr1;
    document.getElementById("result").style.display = "block";
}
 
//鼠标滑过查询结果改变背景样式，根据id打开信息窗体
function openMarkerTipById1(pointid, thiss) {
    thiss.style.background = '#CAE1FF';
    windowsArr[pointid].open(mapObj, marker[pointid]);
}
 
//添加查询结果的marker&infowindow   
function addmarker(i, d) {
    var lngX = d.location.getLng();
    var latY = d.location.getLat();
    var markerOption = {
        map:mapObj,
        icon:"http://webapi.amap.com/images/" + (i + 1) + ".png",
        position:new AMap.LngLat(lngX, latY)
    };
    var mar = new AMap.Marker(markerOption);         
    marker.push(new AMap.LngLat(lngX, latY));
 
    var infoWindow = new AMap.InfoWindow({
        content:"<b><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></b><br>" + TipContents(d.type, d.address, d.tel),
        size:new AMap.Size(300, 0),
        autoMove:true, 
        offset:new AMap.Pixel(0,-30)
    });
    windowsArr.push(infoWindow);
    var aa = function (e) {
		var coords = mar.getPosition();
		infoWindow.open(mapObj, coords);
		coords = coords.toString().split(",");
		$("#lngX").val(coords[0]);
		$("#latY").val(coords[1]);
	};
    AMap.event.addListener(mar, "click", aa);
	
}
 
//infowindow显示内容
function TipContents(type, address, tel) {  //窗体内容
    if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
        type = "暂无";
    }
    if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
        address = "暂无";
    }
    if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
        tel = "暂无";
    }
    var str = "  地址：" + address + "<br />  电话：" + tel + " <br />  类型：" + type;
    return str;
}
function keydown(event){
    var key = (event||window.event).keyCode;
    var result = document.getElementById("result1")
    var cur = result.curSelect;
    if(key===40){//down
        if(cur + 1 < result.childNodes.length){
            if(result.childNodes[cur]){
                result.childNodes[cur].style.background='';
            }
            result.curSelect=cur+1;
            result.childNodes[cur+1].style.background='#CAE1FF';
            document.getElementById("keyword").value = result.tipArr[cur+1].name;
        }
    }else if(key===38){//up
        if(cur-1>=0){
            if(result.childNodes[cur]){
                result.childNodes[cur].style.background='';
            }
            result.curSelect=cur-1;
            result.childNodes[cur-1].style.background='#CAE1FF';
            document.getElementById("keyword").value = result.tipArr[cur-1].name;
        }
    }else if(key === 13){
        var res = document.getElementById("result1");
		if(res && res['curSelect'] !== -1){
			selectResult(document.getElementById("result1").curSelect);
		}
    }else{
        autoSearch();
    }
}
//关键字搜索
function placeSearch(type) {
	var keywords = $('input[name="'+type+'"').val();
    var MSearch;
    AMap.service(["AMap.PlaceSearch"], function() {       
        MSearch = new AMap.PlaceSearch({ //构造地点查询类
            pageSize:10,
            pageIndex:1,
            city:"021" //城市
        });
        //关键字查询
        MSearch.search(keywords, function(status, result){
        	if(status === 'complete' && result.info === 'OK'){
        		keywordSearch_CallBack(result);
        	}
        }); 
    });
}
//回调函数
function keywordSearch_CallBack(data) {
    var resultStr = "";
    var poiArr = data.poiList.pois;
    var resultCount = poiArr.length;alert(resultCount);
    for (var i = 0; i < resultCount; i++) {
        resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h4><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h4>";
            resultStr += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
            addmarker(i, poiArr[i]);
    }
    mapObj.setFitView();
	
    document.getElementById("result").innerHTML = resultStr;
}